import http from '@/utils/request'
import { DictAPIs, EnumDictName } from './dict'

/**科室信息 */
export interface DeptInfo {
  deptCode: string
  deptName: string
  deptAlias: string
  parentDeptCode: string
  parentDeptName: string
  hospitalCode: string
  clinicAttr: string
  outpOrInp: string
  branchCode: string
  internalOrSergeryDesc: string
  editStatus: boolean
  internalOrSergery: string
  position: string
  inputCode: string
}

/**科室树结点 */
export interface DeptTreeNode {
  deptCode: string
  deptName: string
  childrenNodes: DeptTreeNode[]
}

/**科室信息树 */
async function getDeptTree() {
  const depts = await DeptAPIs.getAllDeptInfo()
  const deptTreeNodes: DeptTreeNode[] = []

  depts
    .filter(f => f.parentDeptCode === '')
    .forEach(dept => {
      deptTreeNodes.push({
        deptCode: dept.deptCode,
        deptName: dept.deptName,
        childrenNodes: faltDept(depts, dept.deptCode),
      })
    })

  return deptTreeNodes
}

/**扁平化科室信息 */
function faltDept(depts: DeptInfo[], deptCode: string) {
  const deptTreeNodes: DeptTreeNode[] = []
  depts
    .filter(f => f.deptCode == deptCode)
    .forEach(dept => {
      deptTreeNodes.push({
        deptCode: dept.deptCode,
        deptName: dept.deptName,
        childrenNodes: faltDept(depts, dept.deptCode),
      })
    })
  return deptTreeNodes
}

/**科室信息 */
export const DeptAPIs = {
  /**科室树 */
  getDeptTree,
  /**获取科室信息 */
  getAllDeptInfo() {
    return DictAPIs.getData<DeptInfo>(EnumDictName.科室字典)
  },
  /**获取科室基本信息  */
  getDeptInfo(deptCode: string) {
    return http.get<DeptInfo>(`/sys/getAllDeptInfo`, { deptCode })
  },
  /**保存科室信息 */
  saveDeptInfo(data: DeptInfo) {
    return http.post(`/sys/saveDeptInfo`, data)
  },
  /**删除科室信息 */
  removeDeptInfo(data: DeptInfo) {
    return http.post(`/sys/saveDeptInfo`, data)
  },
}
